<?php

namespace App\Http\Controllers\Manage;

use App\Http\Controllers\ApiController;
use App\Http\Requests\AuxiliaryCheckStoreRequest;
use App\Http\Requests\AuxiliaryCheckUpdateRequest;
use App\Models\Auxiliary\AuxiliaryCheckEntry;
use App\Project\Image\ImageDelete;
use App\Project\Image\ImageUpload;
use App\Transformers\Auxiliary\AuxiliaryCheckEntryTransformer;
use Illuminate\Http\Request;

class AuxiliaryCheckController extends ApiController
{
    protected $model;

    public function __construct(AuxiliaryCheckEntry $entry)
    {
        parent::__construct();
        $this->model = $entry;
    }

    public function show($id)
    {
        $model = $this->model->findOrFail($id);

        return $this->item($model, new AuxiliaryCheckEntryTransformer());
    }

    public function series(Request $request)
    {
        $models = $this->model->where('record_id', $request->input('record_id'))->get();

        return $this->collection($models, new AuxiliaryCheckEntryTransformer());
    }

    public function store(AuxiliaryCheckStoreRequest $request)
    {
        $input  = $request->input();
        $upload = new ImageUpload($request, 'image_file');

        $upload->src()->mergeTo($input, 'images');

        /** @var AuxiliaryCheckEntry $model */
        $model = $this->model->create($input);

        return $this->item($model, new AuxiliaryCheckEntryTransformer());
    }

    public function update($id, AuxiliaryCheckUpdateRequest $request)
    {
        $input = array_intersect_key($request->input(), array_flip(['images', 'remark']));

        if (empty($input)) {
            return $this->setMessage('缺少参数。')->response();
        }

        //  添加新上传的图片
        $upload = new ImageUpload($request, 'image_file');

        $upload->src()->mergeTo($input, 'images');

        $model = $this->model->findOrFail($id);

        $will_delete = $this->imageDelete($model->images, $input['images']);

        $result = $model->fill($input)->save();

        if ($result && $will_delete->count()) {
            $will_delete->delete();
        }

        return $this->responseForUpdate($result);
    }

    protected function imageDelete($should, $leave)
    {
        $delete = new ImageDelete($should);

        return $delete->exclude($leave);
    }
}
